#include "mqtt_ipc.h"

MQTT_IPC::MQTT_IPC(const QHostAddress &host,
                   const quint16 port,
                   const QString &topic,
                   QObject *parent) : QMQTT::Client(host, port, parent)
{
    mSubTopic = topic;
    connect(this, &MQTT_IPC::connected, this, &MQTT_IPC::onConnected);
    connect(this, &MQTT_IPC::disconnected, this, &MQTT_IPC::onDisconnected);
    connect(this, &MQTT_IPC::subscribed, this, &MQTT_IPC::onSubscribed);
    connect(this, &MQTT_IPC::received, this, &MQTT_IPC::onReceived);
}

void MQTT_IPC::mqttConnect()
{
    connectToHost();
}

void MQTT_IPC::mqttDisconnect()
{
    disconnectFromHost();
}

void MQTT_IPC::sendMsg(const QString &topic, const QString &msg)
{
    quint16 retid;

    mMsg = msg;
    mPubTopic = topic;

    QMQTT::Message message(0, mPubTopic, mMsg.toUtf8());
    retid = publish(message);
    qDebug() << "publish message id: " << retid;
}

/**
 * @brief MQTT_IPC::onConnected
 * 连接上后订阅通信用的主题
 */
void MQTT_IPC::onConnected()
{
    qDebug() << "connected";
    subscribe(mSubTopic, 0);
}

void MQTT_IPC::onDisconnected()
{
    qDebug() << "disconnected";
    unsubscribe(mSubTopic);
}

void MQTT_IPC::onSubscribed(const QString &topic)
{
    qDebug() << "subscribed topic, now publish message";
}

void MQTT_IPC::onReceived(const QMQTT::Message &message)
{
    emit recvMsg(message.payload());
}


